const Router = require('@koa/router');
const mongoose = require('mongoose');

const { getBody } = require('../utils/getBody')

const Product = mongoose.model('Product');

const router = new Router({
    prefix: '/product',
});

//添加接口
router.post('/add', async (ctx) => {
    const {
        name,
        price,
        author,
        publishDate,
        classify
    } = getBody(ctx)
    const product = new Product({
        name,
        price,
        author,
        publishDate,
        classify
    });
    const res = await product.save()
    ctx.body = {
        data: res,
        code: 200,
        msg: '添加产品成功'
    }
})
//获取列表
router.get('/list', async (ctx) => {
    //https://aa.cc/com/user?page=1&size=20#fdsdeds query方式page=1&size=20

    let {
        page = 1,
        size = 5,
        keyword = ''
    } = ctx.query
    console.log(size, typeof size);//查看size数据格式
    page = Number(page)
    size = Number(size)
    const query = {}
    if (keyword) {
        query.name = keyword
    }
    //跳过(page-1)*size条数据
    //获取分页数据
    const list = await Product.find(query).skip((page - 1) * size).limit(size).exec()

    //Product集合所有的数据条数
    const total = await Product.countDocuments()

    ctx.body = {
        data: {
            list,
            total,
            page,
            size
        },
        code: 200,
        msg: '获取列表成功'
    }
})

//   /product/123   ctx.params.id
//请求接口    /product/xxx
router.delete('/:id', async (ctx) => {
    const {
        id,
    } = ctx.params;
    const delMsg=await Product.deleteOne({
        _id: id,
    })
    ctx.body={
        data:delMsg,
        msg:'删除成功',
        code:200
    }
})
module.exports = router;
